package com.breaking.second.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.breaking.second.activity.pager.adapter.ImageAdapter;
import com.breaking.second.databinding.ActivityAddGoodsBinding;
import com.breaking.second.databinding.DialogLoadBinding;
import com.breaking.second.entity.BookEntity;
import com.breaking.second.entity.GoodsTypeEntity;
import com.breaking.second.utils.StringUtil;
import com.breaking.second.utils.compat.DialogCompat;
import com.breaking.second.utils.engine.GlideEngine;
import com.breaking.second.utils.okhttp.OkhttpUtil;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class AddGoodsActivity extends BaseActivity<ActivityAddGoodsBinding> implements OnResultCallbackListener<LocalMedia> {
    private final List<String> images = new ArrayList<>();
    private ImageAdapter adapter;
    private final List<GoodsTypeEntity> goodsTypeEntities = new ArrayList<>();
    private ArrayAdapter<String> setAdapter;
    private final List<String> data = new ArrayList<>();
    private AlertDialog alertDialog;
    private String addr = "未知";
    private int type = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initIntent();
        initRecycler();
        initView();
        getTypeData();
        initSpinner();
        getAdd();
    }

    private void initIntent() {
        Intent intent = getIntent();
        type = intent.getIntExtra("type", 0);
    }

    private void getAdd() {
        OkHttpClient client = new OkHttpClient();
        Request.Builder builder = new Request.Builder()
                .url("https://2024.ipchaxun.com/");
        client.newCall(builder.build()).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                ResponseBody responseBody = response.body();
                if (responseBody == null) return;
                String data = responseBody.string();
                System.out.println(data);
                JSONObject jsonObject = JSON.parseObject(data);
                JSONArray array = jsonObject.getJSONArray("data");
                List<String> text = array.toList(String.class);
                if (text == null) return;
                for (int i = 0; i < text.size(); i++) {
                    if (i <= 3) {
                        addr = text.get(i);
                    }
                }
            }
        });
    }

    private void initSpinner() {
        // 创建 ArrayAdapter
        setAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, data);
        setAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // 设置 Adapter 到 Spinner
        binding.type.setAdapter(setAdapter);
    }

    private void getTypeData() {
        OkhttpUtil.Get("goods/type", new OkhttpUtil.CallbackListener(this::getTypeData));
    }

    private void getTypeData(BookEntity bookEntity) {
        if (bookEntity.isCode()) {
            List<GoodsTypeEntity> goodsTypeEntities = bookEntity.toList(GoodsTypeEntity.class);
            if (goodsTypeEntities == null) return;
            if (goodsTypeEntities.isEmpty()) return;
            this.goodsTypeEntities.addAll(goodsTypeEntities);
            for (GoodsTypeEntity goodsTypeEntity : goodsTypeEntities) {
                data.add(goodsTypeEntity.getType());
            }
            setAdapter.notifyDataSetChanged();
        }
    }

    private void initView() {
        binding.addImage.setOnClickListener(this::add_image);
        binding.send.setOnClickListener(this::send);
    }

    private void send(View view) {
        Editable message = binding.content.getText();
        Editable money = binding.money.getText();
        if (images.isEmpty()) {
            Toast.makeText(this, "图片不能为空", Toast.LENGTH_SHORT).show();
            return;
        } else if (StringUtil.isEmpty(message)) {
            Toast.makeText(this, "描述不能为空", Toast.LENGTH_SHORT).show();
            return;
        } else if (StringUtil.isEmpty(money)) {
            Toast.makeText(this, "金额不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        uploadImage();
    }


    private void uploadImage() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        DialogLoadBinding binding = DialogLoadBinding.inflate(getLayoutInflater());
        builder.setView(binding.getRoot());
        alertDialog = builder.show();
        DialogCompat.init(alertDialog.getWindow());
        List<File> files = new ArrayList<>();
        for (String path : images) {
            files.add(new File(path));
        }
        OkhttpUtil.uploadImage(files, new OkhttpUtil.CallbackListener(this::uploadImage));
    }

    private void uploadImage(BookEntity bookEntity) {
        if (alertDialog != null) {
            alertDialog.dismiss();
        }
        if (bookEntity.isCode()) {
            if (bookEntity.getData() instanceof JSONObject data) {
                String imageCode = data.getString("imageCode");
                sendGoods(imageCode);
            }
        }
    }

    private void sendGoods(String imageCode) {
        Editable message = binding.content.getText();
        Editable money = binding.money.getText();
        GoodsTypeEntity goodsTypeEntity = goodsTypeEntities.get(binding.type.getSelectedItemPosition());

        JSONObject form = new JSONObject();
        form.put("addr", addr);
        form.put("content", message.toString());
        form.put("imageCode", imageCode);
        form.put("price", money.toString());
        form.put("typeId", String.valueOf(goodsTypeEntity.getId()));
        form.put("typeName", goodsTypeEntity.getType());
        form.put("userId", String.valueOf(pageableVo.getUserId()));

        if (type == 0) {
            OkhttpUtil.Post("goods/add", form, new OkhttpUtil.CallbackListener(this::sendGoods));
        } else if (type == 1) {
            OkhttpUtil.Post("goods/save", form, new OkhttpUtil.CallbackListener(this::sendGoods));
        }
    }

    private void sendGoods(BookEntity bookEntity) {
        Toast.makeText(this, bookEntity.getMsg(), Toast.LENGTH_SHORT).show();
        if (bookEntity.isCode()) {
            finish();
        }
    }

    private void add_image(View view) {
        PictureSelector.create(this)
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine())
                .forResult(this);
    }

    private void initRecycler() {
        adapter = new ImageAdapter(this, images);
        binding.image.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        binding.image.setAdapter(adapter);
    }

    @Override
    public void onResult(ArrayList<LocalMedia> result) {
        int start = images.size();
        for (LocalMedia localMedia : result) {
            String path = localMedia.getRealPath();
            images.add(path);
        }
        adapter.notifyItemRangeChanged(start, images.size());
    }

    @Override
    public void onCancel() {

    }
}
